import termios, sys, os
import tty
import socket
import SocketServer
import select
#import termios, TERMIOS, sys, os
TERMIOS = termios
class ReusableTCPServer(SocketServer.TCPServer):
    allow_reuse_address = True

class InputServer(SocketServer.BaseRequestHandler):
    def setup(self):
        self.request.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)

    def handle(self):
            stdin_fd = sys.stdin.fileno()
            old = termios.tcgetattr(stdin_fd)
            new = termios.tcgetattr(stdin_fd)
            new[3] = new[3] & ~TERMIOS.ICANON & ~TERMIOS.ECHO
            new[6][TERMIOS.VMIN] = 1
            new[6][TERMIOS.VTIME] = 0
            termios.tcsetattr(stdin_fd, TERMIOS.TCSANOW, new)
            tty.setraw(stdin_fd)
            c = None

            print "Serving ", self.client_address
            try:
                ep_obj = select.epoll()
                ep_obj.register(self.request.fileno(), select.EPOLLIN | select.EPOLLOUT)
                ep_obj.register(stdin_fd, select.EPOLLIN)
                stop = False
                c = ''
                while not stop:
                    events = ep_obj.poll()
                    for fd, event in events:
                        if event & select.EPOLLIN:
                            if fd == stdin_fd:
                                c += os.read(fd, 4)
                                print 'got', ','.join(c), map(ord, c)
                                print '\n\r'
                            else:
                                if len(self.request.recv(1)) == 0: #closed by the peer
                                    print "peer closed the connection"
                                    stop = True
                                    break
                        if event & select.EPOLLOUT:
                            self.request.send(c)
                            c = ''
            finally:
                ep_obj.close()
                #termios.tcsetattr(fd, TERMIOS.TCSAFLUSH, old)

if __name__ == '__main__':
       HOST, PORT= "", 50007 
       server = ReusableTCPServer((HOST, PORT), InputServer)
       server.serve_forever()
